<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <!-- 引入样式 -->
  <link rel="stylesheet" href="../../plugins/element-ui/index.css" />
  <link rel="stylesheet" href="../../styles/common.css" />
  <link rel="stylesheet" href="../../styles/page.css" />
  <style>
    .selectInput {
      position: relative;
      width: 100%;
      min-width: 100px;
    }
    .selectInput .flavorSelect {
      position: absolute;
      width: 100%;
      padding: 0 10px;
      border-radius: 3px;
      border: solid 1px #FF903D;
      line-height: 30px;
      text-align: center;
      background: #fff;
      top: 50px;
      z-index: 99;
    }
    .selectInput .flavorSelect .items {
      cursor: pointer;
      display: inline-block;
      width: 100%;
      line-height: 35px;
      border-bottom: solid 1px #f4f4f4;
      color: #666;
    }
    .selectInput .flavorSelect .none {
      font-size: 14px;
    }

    #food-add-app .uploadImg .el-form-item__label::before{
      content: '*';
      color: #F56C6C;
      margin-right: 4px;
    }
    #img{
      width: 300px;
      height: 300px;
    }


  </style>
</head>
<body >
<div class="dashboard-container" id="food-app">

  <div class="container">



    <div class="tableBar">
      <el-input
              v-model="input"
              placeholder="请输入菜品名称"
              style="width: 250px"
              clearable
              @keyup.enter.native="handleQuery"
      >
        <i
                slot="prefix"
                class="el-input__icon el-icon-search"
                style="cursor: pointer"
                @click="init"
        ></i>
      </el-input>

      <!--        批量删除-->
      <div class="tableLab">
        <span class="span-btn delBut non" @click="deleteHandle('批量', null)">批量删除</span>
        <span class="span-btn blueBug non" @click="statusHandle('1')">批量启售</span>
        <span style="border:none;" class="span-btn delBut non" @click="statusHandle('0')">批量停售</span>
        <el-button
                type="primary"
                @click="dialog('-1')"
        >
          + 新建菜品
        </el-button>
      </div>
    </div>


    <!--      页面数据内容显示-->
    <el-table
            :data="tableData"
            stripe
            class="tableBox"
            @selection-change="handleSelectionChange"
    >
      <el-table-column
              type="selection"
              width="25"
      ></el-table-column>
      <el-table-column
              prop="name"
              label="菜品名称"
      ></el-table-column>
      <el-table-column prop="image" label="图片" align="center">
        <template slot-scope="{ row }">
          <el-image style="width: auto; height: 40px; border:none;cursor: pointer;"
                    :src="getImage(row.image)"
                    :preview-src-list="[ `/common/download?name=${row.image}` ]" >
            <div slot="error" class="image-slot">
              <img src="./../../images/noImg.png"  style="width: auto; height: 40px; border:none;" >
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
              prop="categoryName"
              label="菜品分类"
      ></el-table-column>
      <el-table-column label="售价">
        <template slot-scope="scope">
          <span style="margin-right: 10px;">￥{{ scope.row.price/100 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="售卖状态">
        <template slot-scope="scope">
          <span style="margin-right: 10px;">{{ scope.row.status == '0' ? '停售' : '启售' }}</span>
        </template>
      </el-table-column>
      <el-table-column
              prop="updateTime"
              label="最后操作时间"
      >
      </el-table-column>
      <el-table-column
              label="操作"
              width="160"
              align="center"
      >
        <template slot-scope="scope">
          <el-button
                  type="text"
                  size="small"
                  class="blueBug"
                  @click="dialog(scope.row.id)"
          >
            修改
          </el-button>
          <el-button
                  type="text"
                  size="small"
                  class="blueBug"
                  @click="statusHandle(scope.row)"
          >
            {{ scope.row.status == '0' ? '启售' : '停售' }}
          </el-button>
          <el-button
                  type="text"
                  size="small"
                  class="delBut non"
                  @click="u('单删', scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>




    <!--        页面底角-->
    <el-pagination
            class="pageList"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="counts"
            @size-change="handleSizeChange"
            :current-page.sync="page"
            @current-change="handleCurrentChange"
    ></el-pagination>





  </div>

  <!--        表单-->
  <el-dialog  :visible.sync="dialogFormVisible" width="70%">
    <el-form :model="form" ref="form" :rules="rules">

      <el-form-item label="菜品名称:" :label-width="formLabelWidth" prop="name">
        <el-input v-model="form.name" autocomplete="off" placeholder="请填写菜品名称" maxlength="20"></el-input>
      </el-form-item>

      <el-form-item label="菜品分类:" :label-width="formLabelWidth"  prop="categoryId">
        <!--            <el-input v-model="form.categoryId" autocomplete="off" placeholder="请选择菜品分类"></el-input>-->
        <el-select v-model="form.categoryId" autocomplete="off" placeholder="请选择菜品分类">
          <el-option v-for="(item,index) in dishList" :key="index" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="菜品价格:" :label-width="formLabelWidth"  prop="price">
        <el-input v-model="form.price" autocomplete="off" placeholder="请设置菜品价格"></el-input>
      </el-form-item>

      <!--        口味-->
      <el-form-item label="口味做法配置:" :label-width="formLabelWidth">
        <div class="flavorBox">
          <span v-if="dishFlavors.length == 0" class="addBut" @click="addFlavore" > + 添加口味</span>
          <div v-if="dishFlavors.length != 0" class="flavor">
            <div class="title">
              <span>口味名（3个字内）</span><span>口味标签（输入标签回车添加）</span>
            </div>
            <div class="cont">
              <div v-for="(item, index) in dishFlavors" :key="index" class="items">
                <div class="itTit">
                  <div class="selectInput">
                    <div>
                      <el-input autocomplete="off" v-model="item.name" type="text" style="width: 100%" placeholder="请输入口味" @focus="selectFlavor(true,index)" @blur="outSelect(false,index)"/>
                    </div>
                    <div v-show="item.showOption" class="flavorSelect">
                      <span v-for="(it, ind) in dishFlavorsData" :key="ind" class="items" @click="selectHandle(it,ind,index)">{{ it.name }}</span>
                      <span v-if="dishFlavorsData == []" class="none">无数据</span>
                    </div>
                  </div>
                </div>
                <div class="labItems" style="display: flex">
                  <span v-for="(it, ind) in item.value" :key="ind">{{ it }} <i @click="delFlavorLabel(index, ind)">X</i></span>
                  <div class="inputBox" :style="{'flex':1}" contenteditable="true" @focus="flavorPosition(index)" @keydown.enter="(val)=>keyDownHandle(val,index)"></div>
                </div>
                <span class="delFlavor delBut non" @click="delFlavor(index)">删除</span>
              </div>
            </div>
            <div class="addBut" @click="addFlavore">
              添加口味
            </div>
          </div>
        </div>
      </el-form-item>


      <div>
        <el-form-item label="菜品图片:" prop="region" class="uploadImg" :label-width="formLabelWidth">
          <el-upload class="avatar-uploader" action="/common/upload" :show-file-list="false" :on-success="handleAvatarSuccess" :on-change="onChange" ref="upload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar" id="img"></img>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </div>


      <el-form-item label="菜品描述:" :label-width="formLabelWidth" prop="region">
        <el-input v-model="form.description" autocomplete="off" placeholder="菜品描述，最长200字" type="textarea"  :rows="3" maxlength="200"></el-input>
      </el-form-item>


    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm('form', false)">保 存</el-button>
      <el-button type="info" @click="submitForm('form', true)" :style="{ display: visibleLine }">保存并继续添加</el-button>
      </el-row>
    </div>
  </el-dialog>



</div>
<!-- 开发环境版本，包含了有帮助的命令行警告 -->
<script src="../../plugins/vue/vue.js"></script>
<!-- 引入组件库 -->
<script src="../../plugins/element-ui/index.js"></script>
<!-- 引入axios -->
<script src="../../plugins/axios/axios.min.js"></script>
<script src="../../js/request.js"></script>
<script src="../../api/food.js"></script>
<script>
  new Vue({
    el: '#food-app',
    data() {
      return {
        id : '',
        input: '',
        counts: 0,
        page: 1,
        pageSize: 10,
        tableData : [],
        dishState : '',
        checkList: [],

        visibleLine: '',
        dialogFormVisible: false,

        form: {
          'name': '',
          'id': '',
          'price': '',
          'code': '',
          'image': '',
          'description': '',
          'dishFlavors': [],
          'status': true,
          categoryId: ''
        },
        formLabelWidth: '120px',

        imageUrl: '',
        actionType: '',
        dishList: [],
        dishFlavorsData: [],
        dishFlavors: [],
      }
    },


    computed: {
      rules () {
        return {
          'name': [
            {'required': true, 'message': '请填写菜品名称', 'trigger': 'blur'}
          ],
          'categoryId': [
            {'required': true, 'message': '请选择菜品分类', 'trigger': 'change'}
          ],
          'price': [
            {
              'required': true,
              // 'message': '请填写菜品价格',
              validator: (rules, value, callback) => {
                if (!value) {
                  callback(new Error('请填写菜品价格'))
                } else {
                  const reg = /^\d+(\.\d{0,2})?$/
                  if (reg.test(value)) {
                    if(value < 10000){
                      callback()
                    }else{
                      callback(new Error('菜品价格小于10000'))
                    }
                  } else {
                    callback(new Error('菜品价格格式只能为数字,且最多保留两位小数'))
                  }
                }
              },
              'trigger': 'blur'
            }
          ],
        }
      }
    },



    created() {
      this.init()
    },
    mounted() {
    },
    methods: {

      //初始函数
      async init () {
        const params = {
          page: this.page,
          pageSize: this.pageSize,
          name: this.input ? this.input : undefined
        }
        await getDishPage(params).then(res => {
          if (String(res.code) === '1') {
            this.tableData = res.data.records || []
            this.counts = res.data.total
          }
        }).catch(err => {
          this.$message.error('请求出错了：' + err)
        })
      },



      //-------------------------------------------------------------------------------
      dialog(id){

        getCategoryList({ 'type': 1 }).then(res => {
          if (res.code === 1) {
            this.dishList = res.data
          } else {
            this.$message.error(res.msg || '操作失败')
          }
        })

        this.dishFlavorsData = [
          {'name':'甜味','value':['无糖','少糖','半糖','多糖','全糖']},
          {'name':'温度','value':['热饮','常温','去冰','少冰','多冰']},
          {'name':'忌口','value':['不要葱','不要蒜','不要香菜','不要辣']},
          {'name':'辣度','value':['不辣','微辣','中辣','重辣']}
        ]


        if(id!="-1"){
          this.id="0"
          this.visibleLine = 'none'
          //根据修改id查询数据并且显示
          queryDishById(id).then(res => {
            console.log(res)
            if (String(res.code) === '1') {
              //将数据放到form中
              this.form = { ...res.data }
              //价格处理
              this.form.price = String(res.data.price/100)
              this.form.status = res.data.status
              //将口味转化为json格式
              this.dishFlavors = res.data.flavors.map(obj => ({ ...obj, value: JSON.parse(obj.value),showOption: false }))
              console.log('this.dishFlavors',this.dishFlavors)
              //图片下载
              this.imageUrl = `/common/download?name=${res.data.image}`
            } else {
              this.$message.error(res.msg || '操作失败')
            }
          })
        }else{
          this.visibleLine = ''
          this.form.name="",
                  this.form.id="",
                  this.form.price="",
                  this.form.code="",
                  this.imageUrl="",
                  this.form.description="",
                  this.dishFlavors=[],
                  this.form.status=true,
                  this.form.categoryId=""
          this.id=id
        }
        this.dialogFormVisible=true
      },

      // 按钮 - 添加口味
      addFlavore () {
        //追加口味
        this.dishFlavors.push({'name': '', 'value': [], showOption: false}) // JSON.parse(JSON.stringify(this.dishFlavorsData))
      },


      // 按钮 - 删除口味
      delFlavor (ind) {
        //删除口味
        this.dishFlavors.splice(ind, 1)
      },


      // 按钮 - 删除口味标签
      delFlavorLabel (index, ind) {
        this.dishFlavors[index].value.splice(ind, 1)
      },


      //口味位置记录
      flavorPosition (index) {
        this.index = index
      },


      // 添加口味标签
      keyDownHandle (val,index) {
        if (event) {
          event.cancelBubble = true
          event.preventDefault()
          event.stopPropagation()
        }
        if (val.target.innerText.trim() != '') {
          this.dishFlavors[index].value.push(val.target.innerText)
          val.target.innerText = ''
        }
      },

      //口味获取数据的处理
      selectFlavor(st,index){
        const obj = JSON.parse(JSON.stringify(this.dishFlavors[index]))
        obj.showOption = st
        this.dishFlavors.splice(index,1,obj)

        // this.dishFlavors[index].showOption = st
      },


      //
      outSelect(st,index){

        const _this = this
        setTimeout(()=> {
          const obj = JSON.parse(JSON.stringify(_this.dishFlavors[index]))
          obj.showOption = st
          _this.dishFlavors.splice(index,1,obj)
        }, 200)

      },


      // //
      // checkOption(val, ind, index){
      //   this.selectHandle(val.name, index, ind)
      //   this.dishFlavors[index].name = val.name
      // },



      selectHandle(val, ind,key ){
        const arrDate = [...this.dishFlavors]
        arrDate[key] = JSON.parse(JSON.stringify(this.dishFlavorsData[ind]))
        this.dishFlavors = arrDate
      },



      // 图片
      handleAvatarSuccess (response, file, fileList) {
        // 拼接down接口预览
        if(response.code === 0 && response.msg === '未登录'){
          window.top.location.href = '/backend/page/login/login.html'
        }else{
          this.imageUrl = `/common/download?name=${response.data}`
          this.form.image = response.data
        }
      },

      onChange (file) {
        if(file){
          const suffix = file.name.split('.')[1]
          const size = file.size / 1024 / 1024 < 2
          if(['png','jpeg','jpg'].indexOf(suffix) < 0){
            this.$message.error('上传图片只支持 png、jpeg、jpg 格式！')
            this.$refs.upload.clearFiles()
            return false
          }
          if(!size){
            this.$message.error('上传文件大小不能超过 2MB!')
            return false
          }
          return file
        }
      },




      //保存
      submitForm(form, st) {
        let params = {...this.form}
        // params.flavors = this.dishFlavors
        params.status = this.form.status ? 1 : 0
        params.price *= 100
        params.categoryId = this.form.categoryId
        params.flavors = this.dishFlavors.map(obj => ({ ...obj, value: JSON.stringify(obj.value) }))
        delete params.dishFlavors
        if(!this.imageUrl){
          this.$message.error('请上传菜品图片')
          return
        }
        console.log(this.id)
        console.log(1)
        if (this.id === "-1") {
          if(st){
            delete params.id
            addDish(params).then(res => {
              if (res.code === 1) {
                this.$message.success('菜品添加成功！')
                this.dialogFormVisible = true
              } else {
                this.$message.error(res.msg || '操作失败')
              }
            }).catch(err => {
              this.$message.error('请求出错了：' + err)
            })
          }else {
            delete params.id
            addDish(params).then(res => {
              if (res.code === 1) {
                this.$message.success('菜品添加成功！')
                this.dialogFormVisible = false
                this.handleQuery()
              } else {
                this.$message.error(res.msg || '操作失败')
              }
            }).catch(err => {
              this.$message.error('请求出错了：' + err)
            })
          }
        } else {
          delete params.updateTime
          editDish(params).then(res => {
            if (res.code === 1) {
              this.$message.success('菜品修改成功！')
              this.dialogFormVisible = false
              this.handleQuery()
            } else {
              this.$message.error(res.msg || '操作失败')
            }
          }).catch(err => {
            this.$message.error('请求出错了：' + err)
          })
        }

        // if (this.actionType == 'add') {
        //   delete params.id
        //   addDish(params).then(res => {
        //     if (res.code === 1) {
        //       this.$message.success('菜品添加成功！')
        //       this.dialogFormVisible = false
        //     } else {
        //       this.$message.error(res.msg || '操作失败')
        //     }
        //   }).catch(err => {
        //     this.$message.error('请求出错了：' + err)
        //   })
        // } else {
        //   delete params.updateTime
        //   editDish(params).then(res => {
        //     if (res.code === 1) {
        //       this.$message.success('菜品修改成功！')
        //       this.dialogFormVisible = false
        //     } else {
        //       this.$message.error(res.msg || '操作失败')
        //     }
        //   }).catch(err => {
        //     this.$message.error('请求出错了：' + err)
        //   })
        // }
      },






      //-------------------------------------------------------------------------------------
      //图片下载
      getImage (image) {
        return `/common/download?name=${image}`
      },

      //页面刷新
      handleQuery() {
        this.page = 1;
        this.init();
      },


      // 批量删除
      deleteHandle (type, id) {
        if (type === '批量' && id === null) {
          if (this.checkList.length === 0) {
            return this.$message.error('请选择删除对象')
          }
        }
        this.$confirm('确认删除该菜品, 是否继续?', '确定删除', {
          'confirmButtonText': '确定',
          'cancelButtonText': '取消',
        }).then(() => {
          deleteDish(type === '批量' ? this.checkList.join(',') : id).then(res => {
            if (res.code === 1) {
              this.$message.success('删除成功！')
              this.handleQuery()
            } else {
              this.$message.error(res.msg || '操作失败')
            }
          }).catch(err => {
            this.$message.error('请求出错了：' + err)
          })
        })
      },

      //单个删除
      u (type, id) {
        this.$confirm('确认删除该菜品, 是否继续?', '确定删除', {
          'confirmButtonText': '确定',
          'cancelButtonText': '取消',
        }).then(() => {
          deleteDish(type === '批量' ? this.checkList.join(',') : id).then(res => {
            if (res.code === 1) {
              this.$message.success('删除成功！')
              this.handleQuery()
            } else {
              this.$message.error(res.msg || '操作失败')
            }
          }).catch(err => {
            this.$message.error('请求出错了：' + err)
          })
        })
      },


      //状态更改
      statusHandle (row) {
        let params = {}
        if (typeof row === 'string' ) {
          if (this.checkList.length === 0) {
            this.$message.error('批量操作，请先勾选操作菜品！')
            return false
          }
          params.id = this.checkList.join(',')
          params.status = row
        } else {
          params.id = row.id
          params.status = row.status ? '0' : '1'
        }
        this.dishState = params
        this.$confirm('确认更改该菜品状态?', '提示', {
          'confirmButtonText': '确定',
          'cancelButtonText': '取消',
          'type': 'warning'
        }).then(() => {
          // 起售停售---批量起售停售接口
          dishStatusByStatus(this.dishState).then(res => {
            if (res.code === 1) {
              this.$message.success('菜品状态已经更改成功！')
              this.handleQuery()
            } else {
              this.$message.error(res.msg || '操作失败')
            }
          }).catch(err => {
            this.$message.error('请求出错了：' + err)
          })
        })
      },


      // 批量获取id
      handleSelectionChange (val){
        let checkArr = []
        val.forEach((n) => {
          checkArr.push(n.id)
        })
        this.checkList = checkArr
      },


      handleSizeChange (val) {
        this.pageSize = val
        this.init()
      },


      handleCurrentChange (val) {
        this.page = val
        this.init()
      }
    }
  })
</script>
</body>
</html>